package junior;

import java.util.*;

public class A {
    public static void main(String[] args) {

//        String data = "aAaAab";
        String data = "shusmshuuu";
        System.out.println("S(aa) = " + S(data));


    }
    public static String S(String data){

        String result = "";
        StringBuffer stringBuffer = new StringBuffer();
        Map<Character, Integer> a = new HashMap<>();
        for (int i = 0; i < data.length(); i++) {
            a.put(data.charAt(i),a.getOrDefault(data.charAt(i),0)+1);
        }
        Map<Character, Integer> sortMap = sortMap(a);
        for (Map.Entry<Character, Integer> entry : sortMap.entrySet()){
            for (int i = 0; i < entry.getValue(); i++) {
                stringBuffer.append(entry.getKey());
            }
        }
        for (Map.Entry<Character, Integer> entry : a.entrySet()){
            for (int i = 0; i < entry.getValue(); i++) {
                stringBuffer.append(entry.getKey());
            }
        }
        result = stringBuffer.toString();
        return result;


    }
    public static Map<Character, Integer> sortMap(Map<Character, Integer> map) {
        List<Map.Entry<Character, Integer>> entryList = new ArrayList<>(map.entrySet());
        Collections.sort(entryList, new Comparator<Map.Entry<Character, Integer>>() {
            @Override
            public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
                return o2.getValue() - o1.getValue();
            }
        });
        LinkedHashMap<Character, Integer> linkedHashMap = new LinkedHashMap<Character, Integer>();
        for (Map.Entry<Character,Integer> e : entryList) {
            linkedHashMap.put(e.getKey(),e.getValue());
        }
        return linkedHashMap;
    }

}
